
import { type PaginationProps } from "@pureadmin/table";
import { GetApiInfoDataShareList, GetApiInfoList, AddOrUpdataApiInfoDataShare } from "@/api/stu/bankBigData";
import { useRoute } from "vue-router";
import { ElMessage, FormInstance } from "element-plus";
import { ref, reactive, onMounted } from "vue";
export function useCommon() {
  const route = useRoute();
  const dataList = ref<any>([]);
  const copyText = ref<string>();
  const loading = ref<boolean>(false);
  const BtnLoading = ref<boolean>(false)
  const copyVisible = ref<boolean>(false);
  const newShareVisible = ref<boolean>(false);
  const GetAllDataListPage = ref<any>();
  const regex = /^[\u4e00-\u9fa5]{4,16}$/;// 校验4-16个字中文
  const passwordRegex = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$/ //检验6-12个数字或者字母
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true,
    pageSizes: [5, 10, 15],
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      width: 120
    },
    {
      label: "分享标题",
      prop: "shareTitle",
      minWidth: 300
    },
    {
      label: "分享类型",
      prop: "shareType",
      minWidth: 200,
      cellRenderer: ({ row }) => (
        <span>
          {row.shareType === 1 ? "私有" : "公开"}
        </span>
      )
    },
    {
      label: "有效期",
      prop: "expiration",
      minWidth: 300,
      cellRenderer: ({ row }) => (
        <span>
          {row.expiration === 1 ? "永久有效" : "三天后失效"}
        </span>
      )
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];

  const newShareFrom = reactive({
    shareTitle: "",
    apiInfoDataShareId: [],
    shareType: "",
    safety: "",
    password: "",
    expiration: "",
    isInternalMerge: ""
  })

  const rule = {
    shareTitle: [
      {
        required: true,
        validator: (rule: any, value: any, callback: () => void) => {
          if (regex.test(newShareFrom.shareTitle) === false) {
            return callback(new Error('请输入4-16的中文名称'))
          } else {
            // 校验通过
            return callback()
          }
        },
        trigger: ["blur", "change"],
      }
    ],
    password: [
      {
        required: true,
        validator: (rule: any, value: any, callback: () => void) => {
          if (passwordRegex.test(newShareFrom.password) === false) {
            return callback(new Error('请输入6-12位数字与字母组合'))
          } else {
            // 校验通过
            return callback()
          }
        },
        trigger: ["blur", "change"],
      }
    ],
    apiInfoDataShareId: [
      {
        required: true,
        trigger: ["blur", "change"],
        message: '请选择分享接口',
      }
    ],
    shareType: [
      {
        required: true,
        trigger: ["blur", "change"],
        message: '请选择分享类型',

      }
    ],
    safety: [
      {
        required: true,
        trigger: ["blur", "change"],
        message: '请选择安全性',

      }
    ],
    expiration: [
      {
        required: true,
        trigger: ["blur", "change"],
        message: '请选择有效期',

      }
    ],
    isInternalMerge: [
      {
        required: true,
        trigger: ["blur", "change"],
        message: '请选择是否与存量客户并存',

      }
    ],

  }

  //获取列表数据
  async function getList() {
    const respone = await GetApiInfoDataShareList({
      taskId: route.query.taskId,
      planId: route.query.planId,
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize
    });
    if (respone.success) {
      respone.data?.items.forEach(item => {
        item.createTime = item.createTime.substring(0, 10)
      })
      pagination.total = respone.data?.totalCount
      dataList.value = respone.data?.items;
    } else {
      ElMessage.error(respone.msg);
    }
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
    };
    const respone1 = await GetApiInfoList(data);
    if (respone1.success) {
      GetAllDataListPage.value = respone1.data
    } else {
      ElMessage.error(respone1.msg);
    }
  }

  //分享链接
  function copyUrl(row) {
    copyText.value = row.shareUrl
    const input = document.createElement('input');
    input.value = copyText.value;
    document.body.appendChild(input);
    input.select();
    document.execCommand('copy');
    document.body.removeChild(input);
    ElMessage.success('链接复制成功 请粘贴使用')
  }

  //保存新建分享
  const saveNewShare = (shareFrom: FormInstance | undefined) => {
    (shareFrom as any).validate(async valid => {
      if (!valid) return;
      const data = {
        taskId: route.query.taskId,
        planId: route.query.planId,
        shareTitle: newShareFrom.shareTitle,
        shareType: newShareFrom.shareType,
        safety: newShareFrom.safety,
        isInternalMerge: newShareFrom.isInternalMerge,
        expiration: newShareFrom.expiration,
        password: newShareFrom.password || '',
        userApiInfoIds: newShareFrom.apiInfoDataShareId.join(',')
      };
      BtnLoading.value = true;
      OUTBtnLoding()
      const respone = await AddOrUpdataApiInfoDataShare(data);
      if (respone.success) {
        ElMessage.success(respone.msg);
        cancelsaveNewShare(shareFrom)
        getList()
      } else {
        ElMessage.error(respone.msg);
      }
    })
  }


  //取消新建分享
  function cancelsaveNewShare(row) {
    row.resetFields();
    newShareVisible.value = false
  }
  function handleSizeChange(val) {
    getList()
  }
  function handleCurrentChange(val) {
    // GetMyDataSystem()
    getList()
  }

  function changeShareType() {
    if (newShareFrom.shareType == '2') {
      newShareFrom.safety = 2
    }
  }

  function OUTBtnLoding() {
    setTimeout(() => {
      BtnLoading.value = false
    }, 1000)
  }

  onMounted(() => {
    getList()
  })

  return {
    rule,
    dataList,
    loading,
    BtnLoading,
    copyVisible,
    pagination,
    columns,
    newShareVisible,
    copyText,
    newShareFrom,
    GetAllDataListPage,
    copyUrl,
    saveNewShare,
    cancelsaveNewShare,
    handleSizeChange,
    handleCurrentChange,
    changeShareType
  }
}
